package com.example.studentmanagement2.controller;


import com.example.studentmanagement2.model.Teacher;
import com.example.studentmanagement2.repository.Repository.StudentRepository;


import com.example.studentmanagement2.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

import java.util.List;

@RestController
@RequestMapping("/api/teachers")
public class TeacherController {

    private final TeacherService teacherService;

    @Autowired
    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @GetMapping
    public ResponseEntity<List<Teacher>> getAllTeacher() {
        return ResponseEntity.ok(teacherService.getAllTeachers());
    }

    @PostMapping
    public ResponseEntity<Teacher> addTeacher(@RequestBody Teacher teacher) {
        return new ResponseEntity<>(teacherService.addTeacher(teacher), HttpStatus.CREATED);
    }

    @PutMapping("/{originalId}")  // 路径参数为原始学号
    public ResponseEntity<Teacher> updateTeacher(
            @PathVariable String originalId,  // 原始学号
            @RequestBody Teacher teacher      // 包含新学号的请求体
    ) {
        return ResponseEntity.ok(teacherService.updateTeacher(originalId, teacher));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTeacher(@PathVariable String id) {
        teacherService.deleteTeacher(id);
        return ResponseEntity.noContent().build();
    }
    @GetMapping("/{id}")
    public ResponseEntity<Teacher> getTeacherById(@PathVariable String id) {
        Optional<Teacher> teacher = teacherService.getTeacherById(id);  // 正确调用服务层方法
        return teacher.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
    @GetMapping("/search")
    public ResponseEntity<List<Teacher>> searchTeacher(
            @RequestParam(required = false) String keyword
    ) {
        List<Teacher> teachers = teacherService.searchTeachers(keyword);
        return ResponseEntity.ok(teachers);
    }

}